package com.googlecode.gwtbb.client.shared.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Apr 30, 2008
 */
public class ObjectUtils0 {
	public static <T> int nullSafeCompareTo(Comparable<T> o1, T o2) {
		if (o1 == null)
			return o2 == null ? 0 : -1;
		if (o2 == null)
			return 1;
		return o1.compareTo(o2);
	}

	public static boolean nullSafeEquals(Object o1, Object o2) {
		if (o1 == null)
			return o2 == null;
		return o2 != null && o1.equals(o2);
	}

	public static String nullSafeToString(Object o) {
		return o == null ? null : o.toString();
	}

	public static <T> List<T> copy(List<? extends T> src) {
		if (src == null)
			return null;
		List<T> dest = new ArrayList<T>(src.size());
		// can't use Collections.copy(dest, src); because it needs elements to exist in dest alread
		for (T item : src)
			dest.add(item);
		return dest;
	}

	public static <T> List<T> copyAndSort(List<T> src, Comparator<T> comparator) {
		List<T> copy = copy(src);
		Collections.sort(copy, comparator);
		return copy;
	}

	public static <T extends Enum<T>> T nullSafeEnumValueOf(Class<T> enumType, String name) {
		if (enumType == null || StringUtils.isEmpty(name))
			return null;
		else
			return Enum.valueOf(enumType, name);
	}

	protected ObjectUtils0() {
		throw new UnsupportedOperationException("static invocations only");
	}
}
